<template>
	<mPopup title='请输入验证码' v-model="show"  @confirm="emits('confirm', codeValue)" confirmText="领取额度" >
		<div class="code-box">
			<input v-model="codeValue" cursor-color="transparent" type="number" />
			<view class="items">
				<view class="item" v-for="(_,i) in 6" :key="i">
					{{codeValue[i]}}
				</view>
			</view>
			<view v-if="sending" class="countdown">
				<text class="second">{{countdown}}</text>S后重新获取
			</view>
			<view @click="sendCode" v-else style="color: #2548EF;font-size: 28rpx;margin-top: 30rpx;">
				获取验证码
			</view>
		</div>
	</mPopup>
</template>

<script setup>
	import mPopup from '@/components/mPopup.vue';
	import {ref, watch, watchEffect} from 'vue'
	import {myRequest} from '@/util/api.js'
	const countdown = ref(60);
	const props = defineProps(['mobile']);
	const emits = defineEmits(['confirm'])
	const codeValue = ref('')
	const show = defineModel({type:Boolean})
	let sending = ref(false);
	watch(() => show.value, () => {
		if(show.value){
			if(sending.value === false){
				sendCode()
			}
		}
	})
	
	async function sendCode(){
		sending.value = true
		codeValue.value = ''
		countdown.value  = 60
		try{
			await myRequest({
				url: 'api/sms/sendSmsCode',
				method: 'post',
				data: {
					'mobile': props.mobile,
					'operType': '0'
				}
			});
		}catch(e){
			//TODO handle the exception
			show.value = false
			sending.value = false
			return
		}
		
		uni.showToast({
			title:'验证码发送成功',
			icon:'success'
		})
		
		let timer = setInterval(() => {
			if(countdown.value <= 0){
				clearInterval(timer)
				countdown.value = 0
				sending.value = false
			}else{
				countdown.value--
			}
		},1000)
		show.value = true
	}
</script>

<style lang="scss" scoped>
	.code-box{
		position: relative;
		padding-bottom: 10px;
		input{
			position: absolute;
			height: 100rpx;
			width: 100%;
			color: transparent;
			caret-color: transparent;
		}
		.countdown{
			font-size: 28rpx;
			margin-top: 30rpx;
			color: #A2A2A2;
			.second{
				color: #2548EF;
			}
		}
		.items{
			display: flex;
			justify-content: space-between;
			.item{
				border: 1px dashed #E4E4EA;
				width: 80rpx;
				height: 80rpx;
				color: #3D3D3D;
				font-size: 45rpx;
				text-align: center;
				line-height: 80rpx;
			}
		}
	}
</style>